﻿namespace UFIDA.U9.Cust.SH.SHFastShipBP
{
	using System;
	using System.Collections.Generic;
	using System.Text; 
	using UFSoft.UBF.AopFrame;	
	using UFSoft.UBF.Util.Context;
    using UFIDA.U9.Cust.SH.SHFastShipBE;
    using UFSoft.UBF.Util.DataAccess;
    using System.Data;
    using UFIDA.U9.CC.CreditBP.Proxy;
    using UFIDA.U9.CC.CreditObjectPolicy;
    using UFIDA.U9.CC.CreditSV.Proxy;
    using UFIDA.U9.CC.CreditBP;
    using UFIDA.U9.Cust.SH.SHFastShipBP.SHFastShipBP;
    using UFIDA.U9.Base;
    using UFSoft.UBF.Sys.Database;

	/// <summary>
	/// ShipCreditCheck1 partial 
	/// </summary>	
	public partial class ShipCreditCheck1 
	{	
		internal BaseStrategy Select()
		{
			return new ShipCreditCheck1ImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class ShipCreditCheck1ImpementStrategy : BaseStrategy
	{
		public ShipCreditCheck1ImpementStrategy() { }

		public override object Do(object obj)
		{						
			ShipCreditCheck1 bpObj = (ShipCreditCheck1)obj;
			
			//get business operation context is as follows
			//IContext context = ContextManager.Context	
			
			//auto generating code end,underside is user custom code
			//and if you Implement replace this Exception Code...
			//throw new NotImplementedException();

            if (bpObj.FastShipID <= 0) throw new Exception("快速出货单ID传入为0或负数！");
            SHFastShip fast = SHFastShip.Finder.FindByID(bpObj.FastShipID);
            if (fast == null) throw new Exception("查找快速出货单失败！");

            if (!IsOrgCreditCheck()) return null;

            decimal ShipAmount = 0;
            decimal Credit = 0;
            decimal TmpCredit = 0;
            decimal UsedCredit = 0;
            decimal OverCredit = 0;

            ShipAmount=GetShipAmount(fast);
            GetCredit(fast, ref Credit, ref TmpCredit);
            UsedCredit = GetUsedCredit(fast);
            OverCredit=Credit + TmpCredit - UsedCredit - ShipAmount;

            if ( OverCredit< 0)
            {
                StringBuilder errinfo = new StringBuilder();

                errinfo.AppendLine("信用额度：" + Credit.ToString() + "\r\n");
                errinfo.AppendLine("临时信用额度：" + TmpCredit + "\r\n");
                errinfo.AppendLine("已用额度：" + UsedCredit + "\r\n");
                errinfo.AppendLine("当前单据金额：" + ShipAmount + "\r\n");
                errinfo.AppendLine("超出信用额度：" + OverCredit * -1 + "\r\n");

                throw new Exception(errinfo.ToString());
            }
            return null;
		}

        private bool IsOrgCreditCheck()
        {
            DataSet dskz = new DataSet();
            string sqlkz = @" SELECT b.Value FROM Base_Profile_Trl A ,BASE_ProfileValue b 
                        WHERE a.ID = b.Profile and  A.Name LIKE '%启用信用控制%' and b.Organization = " + Context.LoginOrg.ID;
            int icountkz = DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), sqlkz, null, out dskz);
            if (icountkz > 0)
            {
                if (dskz.Tables[0].Rows[0]["Value"].ToString() == "True")
                {
                    return true;
                }
            }
            return false;
        }

        private decimal GetUsedCredit(SHFastShip fast)
        {
            //客户获取信用等级信息BP 
            GetObjectCreditLevelProxy obj = new GetObjectCreditLevelProxy();
            obj.CustomerCode = fast.Customer.Code;
            ObjectCreditLevelData dto = obj.Do();

            //根据信用等级获得信用占用情况SV
            ObjectCreditLimitStatSVProxy SVobj = new ObjectCreditLimitStatSVProxy();
            SVobj.ObjectCreditLevel = dto.ID;
            CreditLimitRateStatDTOData SVdto = SVobj.Do();

            decimal KHYFS = PubTool.ToDecimal(SVdto.ARBalance.ToString()) + PubTool.ToDecimal(SVdto.BadDebts.ToString())
                                + PubTool.ToDecimal(SVdto.Shipmented.ToString()) + PubTool.ToDecimal(SVdto.Shipmenting.ToString())
                                + PubTool.ToDecimal(SVdto.Ordered.ToString())
                                - PubTool.ToDecimal(SVdto.UndoReturnMoney.ToString()) - PubTool.ToDecimal(SVdto.PreGathering.ToString());
            return KHYFS;

        }

        private void GetCredit(SHFastShip fast, ref decimal Credit, ref decimal TmpCredit)
        {
            string cucode = fast.Customer.Code;

            DataParamList para = new DataParamList();
            para.Add(UFSoft.UBF.Util.DataAccess.DataParamFactory.CreateInput("OrgID", Context.LoginOrg.ID, DbType.Int64));
            para.Add(UFSoft.UBF.Util.DataAccess.DataParamFactory.CreateInput("CustomerCode", cucode, DbType.String));
            para.Add(UFSoft.UBF.Util.DataAccess.DataParamFactory.CreateOutput("Credit", DbType.Decimal));
            para.Add(UFSoft.UBF.Util.DataAccess.DataParamFactory.CreateOutput("TmpCredit", DbType.Decimal));
            DataAccessor.RunSP(DataAccessor.GetConn(), "Cust_GetCredit_Proc", para);
            Credit = PubTool.ToDecimal(para["Credit"].Value.ToString());
            TmpCredit = PubTool.ToDecimal(para["TmpCredit"].Value.ToString());

        }




        private decimal GetShipAmount(SHFastShip fast)
        {
            decimal amount=0;
            foreach (SHFastShipLine line in fast.SHFastShipLine)
            {
                amount += line.Amount;
            }
            return amount;
        }		

	}

	#endregion
	
	
}